<template>
  <el-dialog class="pageIndexFeaturedDialogWrapper" :title="dialogTitle"
             :visible.sync="dialogVisible" width="60%"
             :append-to-body="true" @open="beforeOpen" @close="beforeClose" @closed="afterClose">
    <file-collection-select-dialog v-model="fileCollectionVisible" :title="selectorParams.selectorTitle"
            :multiple="selectorParams.selectorMultiple" :name="selectorParams.selectorName"
            @fileChange="imageSelectorChange"/>
    <goods-search v-model="goodSearchVisible" @change="handleGoodChange"/>
    <div class="featuredBox">
      <div :style="featuredStyle">
        <el-card class="featured" shadow="hover">
          <good-box1 :style="featuredStyle" :click-enable="false" v-bind="form"/>
        </el-card>
      </div>
    </div>
    <xum-title title="参数" :title-span="24" style="margin-top: 20px;"/>
    <el-form ref="form" size="small" :model="form" :rules="formRuler" :disabled="loading" label-width="80px">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="编号" prop="id">
            <el-input type="text" v-model="form.id" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="背景图片" prop="image">
            <el-input type="text" v-model="form.image" :readonly="true">
              <el-button type="text" slot="suffix" icon="el-icon-search" @click="handleSelectImage"/>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="小标题" prop="subTitle">
            <el-input type="text" v-model="form.subTitle"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="标题" prop="title">
            <el-input type="text" v-model="form.title"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="链接商品" prop="linkGoodId">
            <el-input type="text" v-model="form.linkGood['name']" placeholder="点击搜索查询商品" :readonly="true">
              <el-button type="text" icon="el-icon-search"  slot="suffix"
                         @click="openGoodSearchDialog('linkGood')"/>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="方向" prop="direction">
            <el-select v-model="form.direction" placeholder="选择方向" @change="handleDirectionChange">
              <el-option v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button @click="closeDialog" size="small">关闭</el-button>
      <el-button @click="reset" size="small" :disabled="loading">重置</el-button>
      <el-button @click="handleSubmit" type="primary" :loading="loading" size="small">{{submitText}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import XumTitle from '@/components/XumTitle'
import FileCollectionSelectDialog from '@/components/upload/FileCollectionSelectDialog'
import GoodsSearch from '@pages/goods/part/GoodsSearch'
import GoodBox1 from '@/components/good/GoodBox1'
import PageIndexFeaturedInsertDTO, { PageIndexFeaturedDirection } from '@/api/entity/PageIndexFeaturedInsertDTO'
import { eq } from '@/utils/Utils'
import { changeIndexFeatured, insertIndexFeatured } from '@/api/ApiPageIndex'
import { ResultCode } from '@/constants/constants'
import PageIndexFeaturedChangeDTO from '@/api/entity/PageIndexFeaturedChangeDTO'
export default {
  name: 'PageIndexFeaturedDialog',
  components: { GoodBox1, GoodsSearch, FileCollectionSelectDialog, XumTitle },
  props: {
    visible: {
      required: false,
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      required: false,
      default: null
    },
    position: {
      type: String,
      required: true
    },
    width: {
      type: Number,
      required: false,
      default: 506
    },
    height: {
      type: Number,
      required: false,
      default: 255
    }
  },
  model: {
    event: 'visible',
    prop: 'visible'
  },
  data () {
    return {
      submitLoading: false,
      dialogVisible: false,
      fileCollectionVisible: false,
      goodSearchVisible: false,
      optionsList: [{
        value: PageIndexFeaturedDirection.DIRECTION_LEFT,
        label: PageIndexFeaturedDirection.DIRECTION_LEFT
      }, {
        value: PageIndexFeaturedDirection.DIRECTION_RIGHT,
        label: PageIndexFeaturedDirection.DIRECTION_RIGHT
      }],
      selectorParams: {
        selectorTitle: '选择图片',
        selectorMultiple: false,
        selectorName: 'featured'
      },
      initCacheData: {
        id: '',
        title: '',
        subTitle: '',
        image: '',
        imageFileId: '',
        linkGoodId: '',
        linkGood: {
          id: '',
          name: ''
        },
        position: '',
        direction: 'LEFT'
      },
      form: {
        id: '',
        title: '',
        subTitle: '',
        image: '',
        imageFileId: '',
        linkGoodId: '',
        linkGood: {
          id: '',
          name: ''
        },
        position: '',
        direction: 'LEFT'
      },
      formRuler: {
        title: [{
          required: true,
          message: '标题不能为空',
          trigger: ['blur', 'change']
        }],
        image: [{
          required: true,
          message: '图片不能为空',
          trigger: ['blur', 'change']
        }],
        linkGoodId: [{
          required: true,
          message: '链接商品不能为空',
          trigger: ['blur', 'change']
        }],
        direction: [{
          required: true,
          message: '展示方向不能为空',
          trigger: ['blur', 'change']
        }]
      },
      tempForm: {}
    }
  },
  computed: {
    loading () {
      return this.submitLoading
    },
    isEdit () {
      return this.data && this.data.id && this.data.id > 0
    },
    isAdd () {
      return !this.isEdit
    },
    dialogTitle () {
      return this.isEdit ? '编辑数据' : '添加数据'
    },
    submitText () {
      return this.isEdit ? '提交修改' : '添加数据'
    },
    featuredStyle () {
      return {
        height: this.height + 'px',
        width: this.width + 'px'
      }
    }
  },
  methods: {
    initAdd () {
      this.form = Object.assign({}, this.initCacheData)
      this.tempForm = Object.assign({}, this.form)
    },
    initEdit (data) {
      const temp = Object.assign({}, this.initCacheData)
      this.form = Object.assign(temp, data)
      this.tempForm = Object.assign({}, this.form)
    },
    /**
     * 初始化数据
     */
    initData () {
      if (this.isAdd) {
        this.initAdd()
      } else {
        this.initEdit(this.data)
      }
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
      this.fileCollectionVisible = false
      this.goodSearchVisible = false
    },
    /**
     * 对话框打开前初始化数据
     */
    beforeOpen () {
      this.initData()
    },
    /**
     * 对话框关闭前关闭子对话框
     */
    beforeClose () {
      this.fileCollectionVisible = false
      this.goodSearchVisible = false
    },
    /**
     * 对话框关闭后也初始化数据
     */
    afterClose () {
      this.initData()
    },
    /**
     * 对话框关闭按钮关闭对话框
     */
    closeDialog () {
      this.dialogVisible = false
    },
    /**
     * 重置按钮重置对话框数据
     */
    reset () {
      this.initData()
    },
    handleAdd () {
      if (!this.form) {
        this.$message.error('数据错误，form为空')
        return
      }
      if (!this.position) {
        this.$message.error('数据错误，数据位置不能为空')
        return
      }
      this.submitLoading = true
      const params = PageIndexFeaturedInsertDTO.instance()
      params.setSubTitle(this.form.subTitle)
      params.setTitle(this.form.title)
      params.setImage(this.form.image)
      params.setImageFileId(this.form.imageFileId)
      params.setDirection(this.form.direction)
      params.setPosition(this.position)
      params.setLinkGoodId(this.form.linkGoodId)
      insertIndexFeatured(params, data => {
        if (data && data.code === ResultCode.OK) {
          data = data.object
          this.$message.success('添加数据成功')
          this.$emit('change', data)
          this.dialogVisible = false
        }
      }, () => {
        this.submitLoading = false
      })
    },
    handleEdit () {
      if (!this.form || !this.form.id) {
        this.$message.error('数据错误')
        return
      }
      if (!this.form) {
        this.$message.error('数据错误，form为空')
        return
      }
      if (!this.position) {
        this.$message.error('数据错误，数据位置不能为空')
        return
      }
      this.submitLoading = true
      const params = PageIndexFeaturedChangeDTO.instance()
      params.setId(this.form.id)
      params.setSubTitle(this.form.subTitle)
      params.setTitle(this.form.title)
      params.setImage(this.form.image)
      params.setImageFileId(this.form.imageFileId)
      params.setDirection(this.form.direction)
      params.setPosition(this.position)
      params.setLinkGoodId(this.form.linkGoodId)
      changeIndexFeatured(params, data => {
        if (data && data.code === ResultCode.OK) {
          data = data.object
          this.$message.success('修改数据成功')
          this.$emit('change', data)
          this.dialogVisible = false
        }
      }, () => {
        this.submitLoading = false
      })
    },
    /**
     * 提交数据
     */
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.isAdd) {
            this.handleAdd()
          } else {
            if (!eq(this.form, this.tempForm)) {
              this.handleEdit()
            } else {
              this.$message.info('数据未修改')
            }
          }
        }
      })
    },
    /**
     * 选择图片
     */
    handleSelectImage () {
      this.fileCollectionVisible = true
    },
    /**
     * 选择图片发生改变
     */
    imageSelectorChange (list) {
      if (list && typeof list === 'object' && list.length > 0) {
        const item = list[0]
        if (item) {
          this.form.image = item.url
          this.form.imageFileId = item.fileId
        }
      }
    },
    /**
     * 方向改变
     */
    handleDirectionChange (val) {
      if (val && this.form) {
        this.form.direction = val
      }
    },
    /**
     * 打开商品搜索对话框
     */
    openGoodSearchDialog () {
      this.goodSearchVisible = true
    },
    /**
     * 选择商品改变
     */
    handleGoodChange (val) {
      if (val && val.id) {
        this.form.linkGoodId = val.id
        this.form.linkGood = val
      }
    }
  },
  watch: {
    visible (val) {
      this.dialogVisible = val
    },
    dialogVisible (val) {
      this.$emit('visible', val)
    }
  }
}
</script>

<style scoped lang="scss">
  .pageIndexFeaturedDialogWrapper{
    .featuredBox{
      width: 100%;
      display: -webkit-flex;
      display: flex;
      -webkit-justify-content: center;
      justify-content: center;
    }
  }
</style>
